package com.web.bridge.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.web.bridge.dao.IBaseDAO;

@Repository("baseDao")
@Transactional
public class BaseDAOImpl<T> implements IBaseDAO<T> {

	private SessionFactory sessionFactory;
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}

	@Override
	public Serializable save(T t) {
		// TODO Auto-generated method stub
		return getSession().save(t);
	}

	@Override
	public void update(T t) {
		// TODO Auto-generated method stub
		getSession().saveOrUpdate(t);
	}

	@Override
	public void delete(T t) {
		// TODO Auto-generated method stub
		getSession().delete(t);
	}

	@Override
	public T findById(Class<T> entityClazz, Long id) {
		// TODO Auto-generated method stub
		return (T) getSession().get(entityClazz, id);
	}

	@Override
	public List<T> findAll(Class<T> entityClazz) {
		// TODO Auto-generated method stub
		List<T> list = find("from " + entityClazz.getSimpleName());
		return list;
	}

	@Override
	public void delete(Class<T> entityClazz, Long id) {
		// TODO Auto-generated method stub
		getSession().createQuery("delete from "+entityClazz.getSimpleName()+" t where t.id = ?0").setParameter("0", id).executeUpdate();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> find (String hql,Object... params){
		Query query=getSession().createQuery(hql);
		for (int i=0;i<params.length;i++){
			query.setParameter(i+"", params[i]);
		}
		return (List<T>) query.list();
	}

}
